const router = require('koa-router')()
router.prefix('/api/account')
const AppRes = require('../config/app.res')
const { add, findAll, update, deleteById, findOneById } = require('../service/account')

// 新增
router.post('/add', async (ctx, next) => {
  try {
    ctx.body = {
      code: 200,
      msg: AppRes['ADD_SUCCESS'],
      data: await add(ctx.request.body)
    }
  } catch (error) {
    error.status = error.status ? error.status : 500
    ctx.throw(error.status, error)
  }
})

// 查询
router.get('/list', async (ctx, next) => {
  try {
    ctx.body = {
      code: 200,
      msg: AppRes['GET_SUCCESS'],
      data: await findAll(ctx.query, ctx.uid) // 获取 query 参数
    }
  } catch (error) {
    error.status = error.status ? error.status : 500
    ctx.throw(error.status, error)
  }
})

// 修改
router.put('/update', async (ctx, next) => {
  try {
    const res = await update(ctx.request.body, ctx.uid)
    if (res === AppRes['401']) {
      ctx.body = {
        code: 401,
        msg: AppRes['401']
      }
    } else {
      ctx.body = {
        code: 200,
        msg: AppRes['UPDATE_SUCCESS'],
        data: res
      }
    }
  } catch (error) {
    error.status = error.status ? error.status : 500
    ctx.throw(error.status, error)
  }
})

// 删除
router.delete('/deleteById/:id', async (ctx, next) => {
  try {
    const res = await deleteById(ctx.params.id, ctx.uid)
    if (res === AppRes['401']) {
      ctx.body = {
        code: 401,
        msg: AppRes['401']
      }
    } else {
      ctx.body = {
        code: 200,
        msg: AppRes['DELETE_SUCCESS'],
        data: res
      }
    }
  } catch (error) {
    error.status = error.status ? error.status : 500
    ctx.throw(error.status, error)
  }
})

// 根据id查询
router.get('/detail/:id', async (ctx, next) => {
  try {
    ctx.body = {
      code: 200,
      msg: AppRes['GET_SUCCESS'],
      data: await findOneById(ctx.params.id)
    }
  } catch (error) {
    error.status = error.status ? error.status : 500
    ctx.throw(error.status, error)
  }
})

module.exports = router